﻿//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="DylanBox">
// Copyright (c) DylanBox Corporation. All rights reserved.
// </copyright>
// <summary>
//      This real-world code demonstrates the Singleton pattern as a LoadBalancing object. 
//  Only a single instance (the singleton) of the class can be created 
//  because servers may dynamically come on- or off-line 
//  and every request must go throught the one object that has knowledge about the state of the (web) farm. 
// </summary>
// <reference>
//      http://www.dofactory.com/Patterns/PatternSingleton.aspx#intent
//      http://www.cnblogs.com/DylanWind/archive/2008/11/10/1328959.html
// </reference>
// <author>Dylan</author>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SDFL.KeyPoints.DesignPattern.Singleton.Realworld
{
    class Program
    {
        static void Main(string[] args)
        {
            LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
            LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
            LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
            LoadBalancer b4 = LoadBalancer.GetLoadBalancer();

            // Same instance?
            if ((b1 == b2) && (b2 == b3) && (b3 == b4))
                Console.WriteLine("Same instance");

            // All are the same instance -- use b1 arbitrarily 
            // Load balance 15 server requests 
            for (int i = 0; i < 15; i++)
            {
                Console.WriteLine(b1.Server);
            }

            //  that means, whenever we need a server, we can
            LoadBalancer lb = LoadBalancer.GetLoadBalancer(); // lb is singleton!
            Console.WriteLine(lb.Server);

            // Wait for user 
            Console.Read();   
        }
    }
}
